/**
 * Created by apple on 16/4/12.
 */
import { API_URI } from './app.consts'

class Service {
    constructor($http, $q) {
        "ngInject"
        return {
            request : (options) => {
                options = angular.extend({}, options);
                const def = $q.defer();
                let queryUri = API_URI, params;
                if (options.host) queryUri = options.host;
                params = {
                    method : options.method || "GET",
                    url    : queryUri + options.url
                }
                const pwd_rule = /password_rule/.test(options.url);
                switch (params.method.toLowerCase()) {
                    case 'get':
                        params.params = options.data || '';
                        break;
                    case 'post':
                        if (!pwd_rule) {
                            params.headers = {'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'}
                            params.data = $.param(options.data);
                        } else {
                            params.data = options.data;
                        }
                        break;
                    case 'put':
                        params.data = options.data;
                        break;
                    case 'delete':
                        params.url += '/' + options.data.id;
                        params.data = {};
                        break
                }
              /*  if (params.method.match(/post|delete|put/i)) {
                    angular.extend(params, {
                        data    : options.headers ? options.data : $.param(options.data),
                        headers : options.headers || {'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'}
                    })
                }*/
                $http(params).success((data) => {
                    if (data.resultCode === '200') {
                        def.resolve(data);
                    } else {
                        def.reject(data);
                    }
                }).error((data) => {
                    //data.resultMsg = '';
                    def.reject(data);
                });
                return def.promise;
            }
        }
    }
    static factory($http, $q) {
        "ngInject"
        return new Service($http, $q)
    }
}
export default Service;